import 'package:dio/dio.dart';
import 'package:example_example/bean/BossBean.dart';
import 'package:example_example/pages/tabs/WebOrder.dart';
import 'package:example_example/pages/view/LoadingDialog.dart';
import 'package:example_example/pages/view/LoadingWidge.dart';
import 'package:flutter/material.dart';
import '../../util/HttpUtil.dart';
import '../../YColors.dart';
import '../../services/TLSizeFit.dart';
import '../../util/ToastUtils.dart';
import '../../util/DioUtils.dart';
import '../../util/LogUtil.dart';
import '../../util/Storage.dart';
import '../../global/GlobalUrl.dart';
import '../../global/Global.dart';

import 'dart:convert';

import '../Tabs.dart';

/**
 * 密码登录
 * */
class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController _controller_phone = new TextEditingController();
  TextEditingController _controller_code = new TextEditingController();

  /*
   * 手机号码中删除的图标显示的标记
   */
  bool flagShowDeleteImg = false;
  String phoneNumber = "";
  String codeStr = "";

  /*
   * 密码中删除的图标显示的标记
   */
  bool flagCodeDeleteImg = false;

  /*
   * 密码中是否隐藏输入密码显示的标记
   */
  bool flagSeeImg = true;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    TLSizeFit.initialize();
    return Scaffold(
      appBar: AppBar(
        // 标题居中
        elevation: 0,
        //隐藏底部阴影分割线
//        title: Text(
//          "技能标签详细",
//          style: TextStyle(color: YColors.r, fontSize: 18),
//        ),
        backgroundColor: YColors.l, // 设置背景色
//        leading: IconButton(
//          icon: Image.asset(
//            "images/return_back.png",
//            width: 20,
//            height: 20,
//          ),
//          onPressed: () {
//            Navigator.pop(context);
////            Navigator.of(context).pushAndRemoveUntil(
////                new MaterialPageRoute(
////                    builder: (context) => new Tabs(
////                          index: 3,
////                        )),
////                (route) => route == null);
//          },
//        ),
      ),
//      resizeToAvoidBottomPadding: false, //输入框抵住键盘 内容不随键盘滚动
      resizeToAvoidBottomInset: false, //输入框抵住键盘 内容不随键盘滚动
      body: Container(
        color: YColors.l,
        padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(height: TLSizeFit.setPx(20)),
//            Image.asset(
//              "images/redlogo.png",
//              width: TLSizeFit.setPx(78),
//              height: TLSizeFit.setPx(80),
//            ),
            Text(
              "您好！欢迎使用",
              style: TextStyle(fontSize: 32, color: YColors.t),
            ),
            SizedBox(height: 10),

            Container(

              child: Text(
                "神州光大BOSS V3.0",
                style: TextStyle(fontSize: 15, color: YColors.t),
              ),
            ),
            SizedBox(height: 60),
            /**
             * 输入手机号
             * */
            _PhoneView(),
            /**
             * 线
             * */
            Container(
              margin: EdgeInsets.only(top: 0),
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          color: YColors.l, width: 0.3)), //dividerGreenColor
                  color: Colors.white),
            ),
            /**
             * 密码的布局
             * */
            _CodeView(),
            /**
             * 线
             * */
            Container(
              margin: EdgeInsets.only(top: 0),
              decoration: BoxDecoration(
                  border: Border(top: BorderSide(color: YColors.l, width: 0.3)),
                  color: Colors.white),
            ),

//            Container(
//              margin: EdgeInsets.only(top: TLSizeFit.setPx(10)),
//              alignment: Alignment.topRight,
//              child: Text(
//                "忘记密码?",
//                style: TextStyle(fontSize: 14, color: YColors.l),
//              ),
//            ),

            InkWell(
              child: Container(
                margin: EdgeInsets.fromLTRB(TLSizeFit.setPx(10),
                    TLSizeFit.setPx(60), TLSizeFit.setPx(10), 0),
                alignment: Alignment.center,
                height: TLSizeFit.setPx(48),
                child: Text(
                  "登 录",
                  style: TextStyle(fontSize: 18, color: YColors.l),
                ),
                decoration: BoxDecoration(
                  color: YColors.t,
                  borderRadius: BorderRadius.all(// 圆角
                      //  Radius.circular(150),    //圆形
                      Radius.circular(60) // 圆角 zj
                      ),
                ),
              ),
              onTap: () {
                print(phoneNumber);
                print(codeStr);

//                _loginAllData();
                _loginAllDataNew();
//                _ToLogin();
              },
            ),

//            Container(
//              margin: EdgeInsets.only(top: TLSizeFit.setPx(20)),
//              alignment: Alignment.center,
//              child: Row(
//                mainAxisAlignment: MainAxisAlignment.center,
//                children: <Widget>[
//                  Image.asset(
//                    "images/captcha_icon.png",
//                    width: TLSizeFit.setPx(36),
//                    height: TLSizeFit.setPx(40),
//                  ),
//                  Text("验证码登录",
//                      style: TextStyle(fontSize: 16, color: YColors.a)),
//                ],
//              ),
//            ),

//            SizedBox(height: 60),
//            Expanded(
//              flex: 1,
//              child: Container(
//                  margin: EdgeInsets.only(bottom: TLSizeFit.setPx(36)),
//                  alignment: Alignment.bottomCenter,
//                  child: Text('去注册',
//                      style: TextStyle(fontSize: 16, color: YColors.a))),
//            ),
          ],
        ),
      ),
    );
  }

  /**
   * 输入手机号的布局
   * */
  Widget _PhoneView() {
    return Container(
      child: Row(
        children: <Widget>[
          Expanded(
            child: TextField(
              controller: _controller_phone,
              cursorColor: YColors.l,
              // 光标的颜色
              style: TextStyle(
                fontSize: 16,
                color: YColors.t,
              ),
//              keyboardType: TextInputType.phone,
              onChanged: (value) {
                if (value.length > 0) {
                  phoneNumber = value;
                  setState(() {
                    flagShowDeleteImg = true;
                  });
                }
              },
//              maxLength: 30,
              decoration: InputDecoration(
                hintText: "请输入您的账号",
                hintStyle:
                    TextStyle(fontSize: 16, color: YColors.t),
                border: InputBorder.none, // 去掉下滑线
                counterText: '', // 去除输入框底部的字符计数
//                        contentPadding: EdgeInsets.only(top: 0, bottom: -6),//设置文字内容与边框距离
//                         enabledBorder: UnderlineInputBorder(
//                           borderSide: BorderSide(
//                               color: YColors.dividerColor,
//                               width: 0.3), // 默认的下划线的颜色
//                         ),
//                         focusedBorder: UnderlineInputBorder(
//                           borderSide: BorderSide(
//                               color: Color(0xff12BF68),
//                               width: 0.3), // 选中后下划线的颜色
//                         )
              ),
            ),
          ),
          flagShowDeleteImg
              ? InkWell(
                  child: Container(
                    margin: EdgeInsets.only(right: 8),
                    child: Image.asset(
                      "images/cancel_order.png",
                      width: TLSizeFit.setPx(16),
                      height: TLSizeFit.setPx(16),
                    ),
                  ),
                  onTap: () {
                    _controller_phone.clear();
                    phoneNumber = "";
                    setState(() {
                      flagShowDeleteImg = false;
                    });
                  },
                )
              : Container(),
        ],
      ),
    );
  }

  /**
   * 密码的布局
   * */
  Widget _CodeView() {
    return Container(
      margin:
          EdgeInsets.fromLTRB(0, TLSizeFit.setPx(30), 0, TLSizeFit.setPx(4)),
      child: Row(
        children: <Widget>[
          Expanded(
            child: TextField(
              obscureText: flagSeeImg,
              // 密码
              controller: _controller_code,
              cursorColor: YColors.m,
              // 光标的颜色
              style: TextStyle(
                fontSize: 16,
                color: YColors.t,
              ),
//              keyboardType: TextInputType.phone,
              onChanged: (value) {
                if (value.length > 0) {
                  codeStr = value;
                  setState(() {
                    flagCodeDeleteImg = true;
                  });
                }
              },
//              maxLength: 11,
              decoration: InputDecoration(
                hintText: "请输入您的密码",
                hintStyle:
                    TextStyle(fontSize: 16, color: YColors.t),
                border: InputBorder.none, // 去掉下滑线
                counterText: '', // 去除输入框底部的字符计数
//                        contentPadding: EdgeInsets.only(top: 0, bottom: -6),//设置文字内容与边框距离
//                         enabledBorder: UnderlineInputBorder(
//                           borderSide: BorderSide(
//                               color: YColors.dividerColor,
//                               width: 0.3), // 默认的下划线的颜色
//                         ),
//                         focusedBorder: UnderlineInputBorder(
//                           borderSide: BorderSide(
//                               color: Color(0xff12BF68),
//                               width: 0.3), // 选中后下划线的颜色
//                         )
              ),
            ),
          ),

          /**
           * 删除的按钮图标
           * */
          flagCodeDeleteImg
              ? InkWell(
                  child: Container(
                    margin: EdgeInsets.only(right: TLSizeFit.setPx(16)),
                    child: Image.asset(
                      "images/cancel_order.png",
                      width: TLSizeFit.setPx(16),
                      height: TLSizeFit.setPx(16),
                    ),
                  ),
                  onTap: () {
                    _controller_code.clear();
                    codeStr = "";
                    setState(() {
                      flagCodeDeleteImg = false;
                    });
                  },
                )
              : Container(),

          /**
           * 密码是否显示的按钮图标
           * */
          InkWell(
            child: Container(
              margin: EdgeInsets.only(right: TLSizeFit.setPx(8)),
              child: flagSeeImg
                  ? Image.asset(
                      "images/ic_password_normal.png",
                      width: TLSizeFit.setPx(24),
                      height: TLSizeFit.setPx(24),
                    ) //ic_password_show
                  : Image.asset(
                      "images/ic_password_show.png",
                      width: TLSizeFit.setPx(24),
                      height: TLSizeFit.setPx(24),
                    ),
            ),
            onTap: () {
              setState(() {
                flagSeeImg = !flagSeeImg;
              });
            },
          ),
        ],
      ),
    );
  }

  _ToLogin() {
    if (phoneNumber.length <= 0) {
      ToastUtils.toast("请输入手机号");
      return;
    }
    if (codeStr.length <= 0) {
      ToastUtils.toast("密码不能为空哦");
      return;
    }

    String code64 = encodeBase64(codeStr);
    LogUtil.v("登录的密码Base64加密code64：$code64");

    String apiUrl = GlobalUrl.LOGIN_URL_V3;
    print(apiUrl);

    var mapHead = {
      "": "",
    };

//    var map = {
//      "username": phoneNumber,
//      "password": codeStr,
//      "grant_type": "password",
//      "client_id": "app",
//      "client_secret": "Szgd@2021",
//    };

    Map<String, dynamic> map = Map();
    map["username"] = phoneNumber;
    map["password"] = code64;
    map["grant_type"] = "password";
    map["client_id"] = "app";  //clientIdUsUpms
    map["client_secret"] = "Szgd@2021";  //clientSecretUsUpms

    HttpUtil.post(apiUrl, data: map, headers: mapHead, success: (data) {
      print("接口返回的数据：$data");
    }, error: (errorMsg) {
      print("登录....errorMsg: ${errorMsg.toString()}");
    });
  }

  _loginAllDataNew() async {
    if (phoneNumber.length <= 0) {
      ToastUtils.toast("请输入账号");
      return;
    }
    if (codeStr.length <= 0) {
      ToastUtils.toast("密码不能为空哦");
      return;
    }

    LogUtil.v("未加密codeStr：$codeStr");
   String code64 = encodeBase64(codeStr);
    LogUtil.v("登录的密码Base64加密code64：$code64");
//    String deStr =decodeBase64(codeStr);
//    print("解密：$deStr");

    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return new LoadingDialog(text: "努力加载中");
        });

    try {
      String apiUrl = GlobalUrl.LOGIN_URL_V3;
      var dio = Dio();
//      Map<String, dynamic> map = Map();
//      map["username"] = phoneNumber;
//      map["password"] = code64; // 写死的，没有实现 DES加密  // 可否实现Base64加密，后台解密后，再DES加密
//      map["grant_type"] = "password";
//      map["client_id"] = "app"; //clientIdUsUpms app
//      map["client_secret"] = "Szgd@2021"; //clientSecretUsUpms    Szgd@2021

//      apiUrl = "http://192.168.20.114:13012/us-uaa/oauth/token?username=business_admin&password=MTIzNDU2&grant_type=password&client_id=app&client_secret=Szgd@2021";
      apiUrl = GlobalUrl.LOGIN_URL_V3 +"?username="+phoneNumber+"&password="+code64+"&grant_type=password&client_id=app&client_secret=Szgd@2021";
      LogUtil.v("登录的apiUrl：$apiUrl");

      ///发起get请求
//      Response response = await dio.post(apiUrl, queryParameters: map);
      Response response = await dio.post(apiUrl);
      LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
      LogUtil.v("登录的返回数据response：$response");

      var getData = response.data;
      var access_token = getData["access_token"];
//      LogUtil.v("access_token：$access_token");
      var id = getData["id"];
      LogUtil.v("登录的返回数据id：$id");

      if (access_token != null) {
        String strBody = json.encode(getData); // Map 转换成 Json 字符串
        print("strBody: $strBody");
        Storage.setString(Global.LOGINDATA, strBody);

//        var logBean = json.decode(strBody);
//        var access_token = "Bearer " + logBean["access_token"];
//        LogUtil.v("access_token：$access_token");
//        if (id != null && id != "") {
//          _setCheckInfor(id, access_token);
//        }
        //跳转并关闭当前页面
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new WebOrderPage()), // WebOrderPage  Tabs
          (route) => route == null,
        );
      }
    } catch (exception) {
      Navigator.pop(context);
//      _handError(error, '数据请求错误：'+exception.toString());
      LogUtil.v("数据请求错误exception：${exception.toString()}");

//  输入错误密码后的报错：    数据请求错误exception：DioError [DioErrorType.RESPONSE]: Http status error [426]
//      ToastUtils.toast("用户名或密码错误");
      if(exception.toString().contains("426")){
        ToastUtils.toast("用户名不存在或者密码错误");
      }else{
        ToastUtils.toast("数据请求错误");
      }
    }
  }

  _setCheckInfor(id, access_token) async {
    String apiUrlhttp = GlobalUrl.CHECKPASSWORD + "?id=" + id;
    var map = {
      "id": id,
    };
//    LogUtil.v("进来了access_token:" + access_token);
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    var dio = Dio();

    dio.options.headers.addAll(mapHeaders); // 添加headers,如需设置统一的headers信息也可在此添加
    Response response = await dio.get(apiUrlhttp);
    LogUtil.v("进来了data:" + response.data.toString());
//       var str = json.encode(response.data);
    var jsonMap = BossBean.fromJson(response.data);
    String result = jsonMap.code;
    String message = jsonMap.msg;
    bool success = jsonMap.success;
    var getData = jsonMap.data;
    LogUtil.v("进来了getData:" + getData);
    Navigator.pop(context);

    if (success) {
      if (getData != null && getData == 1) {
        //跳转并关闭当前页面
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new Tabs()),
          (route) => route == null,
        );
      } else {
//    传入用户id，返回状态值：1正常；21默认密码未修改；22密码过期；
        LogUtil.v("去修改密码。。");
//        if (getData == 21) {
//          ToastUtils.toast("默认密码未修改,请修改密码");
//        } else if (getData == 22) {
//          ToastUtils.toast("密码过期,请修改密码");
//        }
        Navigator.pushNamed(
            context, "/ChangeCodePage"); //, arguments: {Global.FLAG: "111"}
      }
    } else {
      ToastUtils.toast(message);
    }

//    HttpUtil.get(apiUrlhttp, data: map, headers: mapHeaders, success: (data) {
//      LogUtil.v("进来了data:" + data);
////      进来了data:{code: 200, success: true, data: 21, msg: 操作成功}
//      var jsonMap = BossBean.fromJson(data);
//      String result = jsonMap.code;
//      String message = jsonMap.msg;
//      bool success = jsonMap.success;
//      var getData = jsonMap.data;
//      if(success){
//        if(getData!=null && getData==1){
//          //跳转并关闭当前页面
//        Navigator.pushAndRemoveUntil(
//          context,
//          new MaterialPageRoute(builder: (context) => new Tabs()),
//          (route) => route == null,
//        );
//
//        }else{
//          Navigator.pushNamed(context, "/ChangeCodePage", arguments: {Global.FLAG: getData});
//        }
//      }else{
//        ToastUtils.toast(message);
//      }
//
//
//
//    }, error: (errorMsg) {});
  }

  _loginAllData() async {
    if (phoneNumber.length <= 0) {
      ToastUtils.toast("请输入手机号");
      return;
    }
    if (codeStr.length <= 0) {
      ToastUtils.toast("密码不能为空哦");
      return;
    }
    String baseStr =encodeBase64(codeStr);
    print("加密：$baseStr");
//    String deStr =decodeBase64(baseStr);
//    print("解密：$deStr");

//    I/flutter (32093): 加密：MTIzNDU2
//    I/flutter (32093): 解密：123456

//    'password':''
// 使用
//    var param = {
//      'phonenumber ': phoneNumber,};
//    var param = [
//      { 'phonenumber ': phoneNumber},
//      { 'password': '9812A212F0B6F832'},
//      {'version': "2.8.5"}
//    ];

//    var param = {
//      'phonenumber ': "litingting",
//      'password': "MTIzNDU2",
//      "grant_type": "password",
//      "client_id": "clientIdUsUpms", // app
//      "client_secret": "clientSecretUsUpms",  //   Szgd@2021
//    };

    String apiUrl = GlobalUrl.LOGIN_URL_V3;
    print(apiUrl);
// 注意必须使用 await 修饰
//    var setDesPassword = await Engineer.setDesPassword(codeStr);
//    print("加密后的密setDesPassword码：$setDesPassword");

    http: //10.66.1.100:13012/us-uaa/oauth/token
    // ?username=business_admin&password=123456&grant_type=password&client_id=clientIdUsUpms&client_secret=clientSecretUsUpms

    var dio = Dio();
    Map<String, dynamic> map = Map();
//    map["username"] = "business_admin";
    map["username"] = phoneNumber.toString();
    // map["password"] = '9812A212F0B6F832';   // 写死的，没有实现 DES加密  // 可否实现Base64加密，后台解密后，再DES加密
//    map["password"] = "123456";   // 写死的，没有实现 DES加密  // 可否实现Base64加密，后台解密后，再DES加密
    map["password"] = baseStr.toString(); // 写死的，没有实现 DES加密  // 可否实现Base64加密，后台解密后，再DES加密
//    map["version"] = "2.8.5";
    map["grant_type"] = "password";
    map["client_id"] = "clientIdUsUpms"; //clientIdUsUpms  app
    map["client_secret"] = "clientSecretUsUpms"; //clientSecretUsUpms  Szgd@2021

//    client_id=>app
//    client_secret=>Szgd@2021

    ///发起get请求
//    Response response = await dio.post(apiUrl, queryParameters: param);
    Response response = await dio.post(apiUrl, queryParameters: map);
//    Response response = await dio.get(apiUrl); //  dio 接口请求
//    print(response);
//    print(response.data);  // 打印不全

    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    LogUtil.v("登录的返回数据response：$response");
//    LogUtil.v("access_token：$response.data[access_token]");
//// Json 字符串转化成 Map 类型
//    var logBean  = json.encode(response.data);
//    LogUtil.v("logBean：$logBean");
    var getData = response.data;
    var access_token = getData["access_token"];
    LogUtil.v("access_token：$access_token");

    if (access_token != null) {
//      Storage.setString(Global.LOGINDATA , getData);

      String strBody = json.encode(getData); // Map 转换成 Json 字符串
      print("strBody: $strBody");
      Storage.setString(Global.LOGINDATA, strBody);

//      var str = Storage.getString(Global.LOGINDATA);
//      LogUtil.v("str：$str");

      //跳转并关闭当前页面
      Navigator.pushAndRemoveUntil(
        context,
        new MaterialPageRoute(builder: (context) => new Tabs()),
        (route) => route == null,
      );
    }

//    if (response.data.length > 0) {
//      String result = response.data[Global.RESULT];  // "result"
//      print("result:$result");
//      if (result == "success") {  // "success"
//        var body = response.data[Global.BODY];  // "body"
//        String strBody = json.encode(body);  // Map 转换成 Json 字符串
//        print("strBody: $strBody");
////        print("body:$body");
//        Storage.setString(Global.LOGINDATA, response);
//
////        Navigator.pop(context);
//      } else {
//        String message = response.data[Global.MESSAGE];
//        ToastUtils.toast(message);
//      }
//    }

//    DioUtils.requestHttp(
//      GlobalUrl.LOGIN_URL_V3,
//      parameters: param,
//      method: DioUtils.GET,
//      onSuccess: (data) {
//        print("登录的接口data：$data");
//      },
//      onError: (error) {
//        print("登录的接口error：$error");
//      },
//    );
  }

  /*
  * Base64加密
  */
  static String encodeBase64(String data) {
    var content = utf8.encode(data);
    var digest = base64Encode(content);
    return digest;
  }

/*
  * Base64解密
  */
  static String decodeBase64(String data) {
    return String.fromCharCodes(base64Decode(data));
  }
}
